//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package 力扣.题库.未分类;

public class demo_2444 {
    public demo_2444() {
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 4, 3, 4, 2, 2, 3, 3};
        System.out.println(countSubarrays(nums, 2, 4));
    }

    public static long countSubarrays(int[] nums, int minK, int maxK) {
        int min = -1;
        int max = -1;
        int out = -1;
        int n = nums.length;
        long count = 0L;

        for(int i = 0; i < n; ++i) {
            int num = nums[i];
            if (num == minK) {
                min = i;
            }

            if (num == maxK) {
                max = i;
            }

            if (num < minK || num > maxK) {
                out = i;
            }

            count += (long)Math.max(Math.min(min, max) - out, 0);
        }

        return count;
    }
}
